﻿using Earthwatchers.Data;
using Earthwatchers.Models;

namespace Earthwatchers.Services.Security.MembershipProviders
{
    public class TigMembershipProvider:IMembershipProvider
    {
        private readonly string connectionString;

        public TigMembershipProvider(string connectionString)
        {
            this.connectionString = connectionString;
        }

        public bool ValidateUser(string username, string password)
        {
            var isValid = false;
            var settingsRepository = new SettingsRepository(connectionString);
            var authenticationUrl = settingsRepository.GetSetting("TigAuthenticationUrl").Val;
            var chunkPasswordStart = int.Parse(settingsRepository.GetSetting("TigAuthenticationPwStart").Val);
            var chunkPasswordLength = int.Parse(settingsRepository.GetSetting("TigAuthenticationPwEnd").Val);

            if (password.Length == chunkPasswordLength)
            {
                var url = string.Format(authenticationUrl, username, password);
                isValid = TigAuthenticationWebClient.Authenticate(url);
            }
            if (!isValid)
            {
                var authkey = Authenticate.GetAuthKey(password, chunkPasswordStart, chunkPasswordLength);
                var checkurl = string.Format(authenticationUrl, username, authkey);
                isValid = TigAuthenticationWebClient.Authenticate(checkurl);
            }

            return isValid;
        }
    }
}